import { useModel } from "umi";
import { useReactive } from "ahooks";

import { AllOrganizationApplicationDevelopers, ChangeOrganizationApplicationDeveloperStatus } from "../../_graphql/developer";

const useDeveloper = () => {
    const { graphqlFetchPlatform, remoteData } = useModel("global");

    const state = useReactive({
        dataLoading: false,
        submitLoading: false,
        developers: [],
    });

    const loadDevelopers = async () => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({ query: AllOrganizationApplicationDevelopers, variables: {} });
        state.developers = res?.a?.nodes.map((item) => ({ oadStat: item.oadStat, oadCrti: item.oadCrti, ...item.b })) || [];
        state.selectedDeveloper = state.developers.find((item) => item.oiUscc === state.selectedDeveloper?.oiUscc);
        !state.selectedDeveloper && state.developers.length > 0 && (state.selectedDeveloper = state.developers[0]);
        state.dataLoading = false;
    };

    const changeDeveloperStatus = async (oiUscc, oadStat, callback) => {
        state.submitLoading = true;
        let res = await graphqlFetchPlatform({
            query: ChangeOrganizationApplicationDeveloperStatus,
            variables: { oiUscc, oadStat },
        });
        res && callback && callback(res);
        state.submitLoading = false;
    };

    const addDeveloper = async (oiUscc, callback) => {
        state.submitLoading = true;
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceName: "/operator/developer/add",
            params: { oiUscc },
        });
        res && callback && callback(res);
        state.submitLoading = false;
    };

    return { ...state, loadDevelopers, changeDeveloperStatus, addDeveloper };
};

export default useDeveloper;
